package com.funtonow.jqdk.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.LoanListAdapter;
import com.funtonow.jqdk.base.BaseFragment;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.ui.LoginActivity;
import com.funtonow.jqdk.ui.VipActivity;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.AutoSwipeRefreshView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Call;

import static com.funtonow.jqdk.base.Constants.INTO_LIST;
import static com.funtonow.jqdk.base.UrlUtils.HOME_LIST;

/**
 * @author Jiajien
 * @date 2019/6/22
 */
public class LoanListFragment extends BaseFragment {

    @BindView(R.id.auto_refresh)
    AutoSwipeRefreshView autoSwipeRefreshView;
    @BindView(R.id.rlv_loan_list)
    RecyclerView mRlvLoanList;

    private LoanListAdapter loanListAdapter;
    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();
    private List<GameThirdInfoListBean> allLoanList = new ArrayList<>();

    public static LoanListFragment newInstance() {
        Bundle args = new Bundle();
        LoanListFragment fragment = new LoanListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View getLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_loan, null);
    }

    @Override
    public void onCreateFragment(@Nullable Bundle savedInstanceState) {
        initRecyclerView(mRlvLoanList);
        loanListAdapter = new LoanListAdapter();
        mRlvLoanList.setAdapter(loanListAdapter);
        autoSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (allLoanList.size() > 0) {
                    allLoanList.clear();
                }
                getAppId();
            }
        });
        if (SqjAppliaction.loanInfoBean == null) {
            autoSwipeRefreshView.autoRefresh();
        } else {
            setLoanData(SqjAppliaction.loanInfoBean);
        }
        StatisticsUtils.baoGuang(Constants.HEZI_ID_22);
        loanListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() == null) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                } else if (SPUtil.getUserInfo() != null && loanListAdapter.getItem(position).getVipfw() == 1
                        && SPUtil.getUserInfo().getHasVip() == 0) {
                    ToastUtils.show("该产品仅限会员申请");
                    startActivity(new Intent(getActivity(), VipActivity.class));
                } else {
                    StatisticsUtils.clickUrl(loanListAdapter.getItem(position));
                    StatisticsUtils.intentWebView(getActivity(),
                            loanListAdapter.getItem(position).getUrl(), loanListAdapter.getItem(position).getName(),
                            loanListAdapter.getItem(position).getChanpinid());
                }
            }
        });
        StatisticsUtils.eventLog(INTO_LIST, null);
    }


    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    private void getLoanList() {
        Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.DATA_APP_ID);
        param.put("app", "1");
        HttpUtil.getInstance().postDataAsynToNet(HOME_LIST, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                autoSwipeRefreshView.setRefreshing(false);
                setLoanData(JSON.parseObject(jsonString, LoanInfoBean.class));
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void setLoanData(LoanInfoBean loanInfoBean) {
        if (gameThirdInfoListBeans.size() > 0) {
            gameThirdInfoListBeans.clear();
        }
        JSONObject jsonObject = JSON.parseObject(loanInfoBean.getCpMap());
        if (loanInfoBean.getHeziInfoList() != null) {
            for (LoanInfoBean.HeziInfoListBean heziInfoListBean : loanInfoBean.getHeziInfoList()) {
                if (heziInfoListBean.getType() == 22) {
                    for (LoanInfoBean.GdlistBean gdlistBean : loanInfoBean.getGdlist()) {
                        if (heziInfoListBean.getGdid().equals(gdlistBean.getGdid())) {
                            GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                            gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                            gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                            gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                            gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                            gameThirdInfoListBean.setGdId(gdlistBean.getGdid());
                            gameThirdInfoListBeans.add(gameThirdInfoListBean);
                        }
                    }
                }
            }
            for (int i = 0; i < 5; i++) {
                allLoanList.addAll(gameThirdInfoListBeans);
            }
            loanListAdapter.setNewData(allLoanList);
        }
    }

    /**
     * 获取数据appId
     */
    private void getAppId() {
        HttpUtil.getInstance().getDataAsynFromNet(UrlUtils.GET_APPID, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {

                Constants.DATA_APP_ID = JSON.parseObject(jsonString).getString("appId");
                getLoanList();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

}
